package ca.kooki.codesnippet.core;

import java.util.ArrayList;
import java.util.List;


public class SearchInput {

  //```````````````````````
  // MEMBER VARIABLES
  //```````````````````````

  private User _from;
  private String _input;
  private String _username;
  private List<String> _allSearchTerms;
  
  //```````````````````````
  // CONSTRUCTOR
  //```````````````````````

  public SearchInput()
  {
    init(User.ANNONYMOUS,"");
  }
  
  public SearchInput(String input)
  {
    init(User.ANNONYMOUS,input);
  }
  
  public SearchInput(User from, String input)
  {
    init(from,input);
  }
  
  private void init(User from, String input)
  {
    _from = from;
    _input = input;
    _username = "";
    _allSearchTerms = new ArrayList<String>();

    if (input == null)
    {
      return;
    }
    
    if (input.startsWith("/"))
    {
      configurePath();
    }
    else
    {
      configureSearchTerms();
    }
  }
  
  //```````````````````````
  // INTERFACE
  //```````````````````````
  
  public User from()
  {
    return _from;
  }
  
  public boolean isAll()
  {
    return _input == null || _input.equals("") || _input.equals("/");
  }
  
  public boolean hasUsername()
  {
    return _username != "";
  }
  
  public String getUsername()
  {
    return _username;
  }
  
  public boolean isRelevantTo(String keywords)
  {
    if (keywords == null || keywords.equals("") || _allSearchTerms.size() == 0)
    {
      return true;
    }
    
    String[] allKeywords = keywords.split(" ");
    for (int i=0; i<allKeywords.length; i++)
    {
      if (_allSearchTerms.contains(allKeywords[i]))
      {
        return true;
      }
    }
    return false;
  }

  public String getSearchQuery()
  {
    return _input;
  }
  

  //```````````````````````
  // PRIVATE METHODS
  //```````````````````````

  private void configurePath()
  {
    String[] allQueries = _input.split("/");
    for (int i=0; i<allQueries.length; i++)
    {
      String nextQueryElement = allQueries[i];
      if (nextQueryElement.equals(""))
      {
        continue;
      }
      if (_username.equals(""))
      {
        _username = nextQueryElement;
      }
      else
      {
        _allSearchTerms.add(nextQueryElement);
      }
    }
  }
  
  private void configureSearchTerms()
  {
    String[] allQueries = _input.split(" ");
    for (int i=0; i<allQueries.length; i++)
    {
      String nextQueryElement = allQueries[i];
      if (nextQueryElement.equals(""))
      {
        continue;
      }
      _allSearchTerms.add(nextQueryElement);
    }
  }
  
}
